import './style.css';
import { PasswordManager } from './password-manager';
import type { PasswordTemplate, AppState } from './types';

class MPWApp {
  private passwordManager: PasswordManager;
  private appElement: HTMLElement;

  constructor() {
    this.passwordManager = new PasswordManager();
    this.appElement = document.querySelector('#app')!;

    // 订阅状态变化
    this.passwordManager.subscribe((state) => {
      this.render(state);
    });

    // 初始渲染
    this.render(this.passwordManager.getState());
  }

  private render(state: AppState): void {
    if (state.isLoggedIn) {
      this.renderMainApp(state);
    } else {
      this.renderLoginPage(state);
    }
  }

  private renderLoginPage(state: AppState): void {
    this.appElement.innerHTML = `
      <div class="login-container">
        <div class="login-card card">
          <div class="card-body">
            <div class="login-header">
              <h1 class="login-title">MPW 密码管理器</h1>
              <p class="login-subtitle">使用主密码安全生成所有网站密码</p>
            </div>

            ${state.error ? `
              <div class="alert alert-error">
                ${state.error}
              </div>
            ` : ''}

            <form id="login-form">
              <div class="form-group">
                <label class="form-label" for="user-name">用户名</label>
                <input
                  type="text"
                  id="user-name"
                  class="form-input"
                  placeholder="输入您的用户名"
                  required
                  autocomplete="username"
                />
              </div>

              <div class="form-group">
                <label class="form-label" for="master-password">主密码</label>
                <input
                  type="password"
                  id="master-password"
                  class="form-input"
                  placeholder="输入您的主密码"
                  required
                  autocomplete="current-password"
                />
              </div>

              <button
                type="submit"
                class="btn btn-primary btn-lg w-full"
                ${state.isLoading ? 'disabled' : ''}
              >
                ${state.isLoading ? '<span class="loading"></span> 登录中...' : '登录'}
              </button>
            </form>

            <div class="mt-4 text-center text-sm text-muted">
              <p>主密码不会被存储，仅用于生成网站密码</p>
            </div>
          </div>
        </div>
      </div>
    `;

    // 绑定登录表单事件
    const loginForm = document.getElementById('login-form') as HTMLFormElement;
    loginForm.addEventListener('submit', this.handleLogin.bind(this));

    // 清除错误信息
    if (state.error) {
      setTimeout(() => {
        this.passwordManager.clearError();
      }, 5000);
    }
  }

  private async handleLogin(event: Event): Promise<void> {
    event.preventDefault();

    const userName = (document.getElementById('user-name') as HTMLInputElement).value.trim();
    const masterPassword = (document.getElementById('master-password') as HTMLInputElement).value;

    if (!userName || !masterPassword) {
      return;
    }

    try {
      await this.passwordManager.login(userName, masterPassword);
    } catch (error) {
      // 错误已经在 PasswordManager 中处理
      console.error('Login failed:', error);
    }
  }

  private renderMainApp(state: AppState): void {
    this.appElement.innerHTML = `
      <div class="main-header">
        <div class="container">
          <div class="header-content">
            <h1 class="header-title">MPW 密码管理器</h1>
            <div class="header-user">
              <span>欢迎, ${state.currentUser?.name}</span>
              <span>•</span>
              <span>${state.currentUser?.sites.length || 0} 个网站</span>
            </div>
            <div class="header-actions">
              <button class="btn btn-secondary btn-sm" id="settings-btn">
                ⚙️ 设置
              </button>
              <button class="btn btn-secondary btn-sm" id="logout-btn">
                🚪 退出
              </button>
            </div>
          </div>
        </div>
      </div>

      <div class="main-content">
        <div class="container">
          <div class="sidebar">
            <div class="sites-header">
              <h2 class="sites-title">网站列表</h2>
              <button class="btn btn-primary btn-sm" id="add-site-btn">
                ➕ 添加网站
              </button>
            </div>

            <div id="sites-list">
              ${this.renderSitesList(state)}
            </div>
          </div>

          <div class="content-area">
            ${this.renderContentArea(state)}
          </div>
        </div>
      </div>

      ${this.renderModals(state)}
    `;

    this.bindMainAppEvents();
  }

  private renderSitesList(state: AppState): string {
    if (!state.currentUser?.sites.length) {
      return `
        <div class="empty-state">
          <div class="empty-state-icon">🌐</div>
          <div class="empty-state-title">暂无网站</div>
          <div class="empty-state-description">点击"添加网站"开始管理您的密码</div>
        </div>
      `;
    }

    const sortedSites = [...state.currentUser.sites].sort((a, b) => b.lastUsed - a.lastUsed);

    return `
      <ul class="site-list">
        ${sortedSites.map(site => `
          <li class="site-item ${state.selectedSite?.id === site.id ? 'active' : ''}"
              data-site-id="${site.id}">
            <div class="site-item-content">
              <div class="site-name">${this.escapeHtml(site.name)}</div>
              <div class="site-url">${this.escapeHtml(site.siteName)}</div>
              <div class="site-meta">
                <span>计数器: ${site.counter}</span>
                <span>模板: ${this.passwordManager.getTemplateInfo(site.template).name}</span>
              </div>
            </div>
          </li>
        `).join('')}
      </ul>
    `;
  }

  private renderContentArea(state: AppState): string {
    if (!state.selectedSite) {
      return `
        <div class="empty-state">
          <div class="empty-state-icon">🔐</div>
          <div class="empty-state-title">选择一个网站</div>
          <div class="empty-state-description">从左侧列表中选择一个网站来生成密码</div>
        </div>
      `;
    }

    const templateInfo = this.passwordManager.getTemplateInfo(state.selectedSite.template);

    return `
      <div class="password-section card">
        <div class="card-header">
          <h3 class="card-title">${this.escapeHtml(state.selectedSite.name)}</h3>
        </div>
        <div class="card-body">
          <div class="password-display">
            <input
              type="text"
              id="generated-password"
              class="password-input form-input ${state.currentUser?.settings.showPassword ? '' : 'hidden'}"
              readonly
              placeholder="点击生成密码"
            />
          </div>

          <div class="password-actions">
            <button class="btn btn-primary" id="generate-password-btn">
              🔄 生成密码
            </button>
            <button class="btn btn-secondary" id="copy-password-btn" disabled>
              📋 复制密码
            </button>
            <button class="btn btn-secondary" id="toggle-password-btn">
              ${state.currentUser?.settings.showPassword ? '🙈 隐藏' : '👁️ 显示'}
            </button>
          </div>
        </div>
      </div>

      <div class="site-details card">
        <div class="card-header">
          <h3 class="card-title">网站设置</h3>
        </div>
        <div class="card-body">
          <div class="site-controls">
            <div class="form-group">
              <label class="form-label" for="site-counter">计数器</label>
              <input
                type="number"
                id="site-counter"
                class="form-input"
                value="${state.selectedSite.counter}"
                min="1"
                max="4294967295"
              />
            </div>

            <div class="form-group">
              <label class="form-label" for="site-template">密码模板</label>
              <select id="site-template" class="form-select">
                ${this.renderTemplateOptions(state.selectedSite.template)}
              </select>
            </div>
          </div>

          <div class="form-group">
            <label class="form-label" for="site-context">上下文 (可选)</label>
            <input
              type="text"
              id="site-context"
              class="form-input"
              value="${state.selectedSite.context || ''}"
              placeholder="用于区分同一网站的不同账户"
            />
          </div>

          <div class="template-info">
            <div class="template-name">${templateInfo.name}</div>
            <div class="template-description">${templateInfo.description}</div>
            <div class="template-example">示例: ${templateInfo.example}</div>
          </div>

          <div class="flex gap-2">
            <button class="btn btn-primary" id="update-site-btn">
              💾 保存更改
            </button>
            <button class="btn btn-danger" id="delete-site-btn">
              🗑️ 删除网站
            </button>
          </div>
        </div>
      </div>
    `;
  }

  private renderTemplateOptions(selectedTemplate: PasswordTemplate): string {
    const templates: PasswordTemplate[] = ['maximum', 'long', 'medium', 'basic', 'short', 'pin', 'name', 'phrase'];

    return templates.map(template => {
      const info = this.passwordManager.getTemplateInfo(template);
      return `
        <option value="${template}" ${template === selectedTemplate ? 'selected' : ''}>
          ${info.name} - ${info.description}
        </option>
      `;
    }).join('');
  }

  private renderModals(state: AppState): string {
    let modals = '';

    // 添加网站模态框
    if (state.showAddSite) {
      modals += `
        <div class="modal-overlay" id="add-site-modal">
          <div class="modal">
            <div class="modal-header">
              <h3 class="modal-title">添加新网站</h3>
              <button class="modal-close" id="close-add-site-modal">×</button>
            </div>
            <div class="modal-body">
              <form id="add-site-form">
                <div class="form-group">
                  <label class="form-label" for="new-site-name">网站名称</label>
                  <input
                    type="text"
                    id="new-site-name"
                    class="form-input"
                    placeholder="例如: Google"
                    required
                  />
                </div>

                <div class="form-group">
                  <label class="form-label" for="new-site-url">网站域名</label>
                  <input
                    type="text"
                    id="new-site-url"
                    class="form-input"
                    placeholder="例如: google.com"
                    required
                  />
                </div>

                <div class="form-group">
                  <label class="form-label" for="new-site-template">密码模板</label>
                  <select id="new-site-template" class="form-select">
                    ${this.renderTemplateOptions(state.currentUser?.settings.defaultTemplate || 'long')}
                  </select>
                </div>

                <div class="form-group">
                  <label class="form-label" for="new-site-context">上下文 (可选)</label>
                  <input
                    type="text"
                    id="new-site-context"
                    class="form-input"
                    placeholder="用于区分同一网站的不同账户"
                  />
                </div>
              </form>
            </div>
            <div class="modal-footer">
              <button class="btn btn-secondary" id="cancel-add-site">取消</button>
              <button class="btn btn-primary" id="confirm-add-site">添加网站</button>
            </div>
          </div>
        </div>
      `;
    }

    // 设置模态框
    if (state.showSettings) {
      modals += `
        <div class="modal-overlay" id="settings-modal">
          <div class="modal">
            <div class="modal-header">
              <h3 class="modal-title">设置</h3>
              <button class="modal-close" id="close-settings-modal">×</button>
            </div>
            <div class="modal-body">
              <div class="form-group">
                <label class="form-label" for="default-template">默认密码模板</label>
                <select id="default-template" class="form-select">
                  ${this.renderTemplateOptions(state.currentUser?.settings.defaultTemplate || 'long')}
                </select>
              </div>

              <div class="form-group">
                <label class="form-label">
                  <input
                    type="checkbox"
                    id="auto-lock"
                    ${state.currentUser?.settings.autoLock ? 'checked' : ''}
                  />
                  启用自动锁定
                </label>
              </div>

              <div class="form-group">
                <label class="form-label" for="auto-lock-timeout">自动锁定时间 (分钟)</label>
                <input
                  type="number"
                  id="auto-lock-timeout"
                  class="form-input"
                  value="${state.currentUser?.settings.autoLockTimeout || 15}"
                  min="1"
                  max="1440"
                />
              </div>

              <div class="form-group">
                <label class="form-label">
                  <input
                    type="checkbox"
                    id="show-password"
                    ${state.currentUser?.settings.showPassword ? 'checked' : ''}
                  />
                  默认显示密码
                </label>
              </div>
            </div>
            <div class="modal-footer">
              <button class="btn btn-secondary" id="cancel-settings">取消</button>
              <button class="btn btn-primary" id="save-settings">保存设置</button>
            </div>
          </div>
        </div>
      `;
    }

    return modals;
  }

  private bindMainAppEvents(): void {
    // 头部按钮事件
    document.getElementById('logout-btn')?.addEventListener('click', () => {
      this.passwordManager.logout();
    });

    document.getElementById('settings-btn')?.addEventListener('click', () => {
      this.passwordManager.showSettingsDialog();
    });

    document.getElementById('add-site-btn')?.addEventListener('click', () => {
      this.passwordManager.showAddSiteDialog();
    });

    // 网站列表点击事件
    document.querySelectorAll('.site-item').forEach(item => {
      item.addEventListener('click', () => {
        const siteId = item.getAttribute('data-site-id');
        if (siteId) {
          const state = this.passwordManager.getState();
          const site = state.currentUser?.sites.find(s => s.id === siteId);
          if (site) {
            this.passwordManager.selectSite(site);
          }
        }
      });
    });

    // 密码生成和操作事件
    document.getElementById('generate-password-btn')?.addEventListener('click', async () => {
      await this.handleGeneratePassword();
    });

    document.getElementById('copy-password-btn')?.addEventListener('click', () => {
      this.handleCopyPassword();
    });

    document.getElementById('toggle-password-btn')?.addEventListener('click', () => {
      this.handleTogglePasswordVisibility();
    });

    // 网站设置事件
    document.getElementById('update-site-btn')?.addEventListener('click', () => {
      this.handleUpdateSite();
    });

    document.getElementById('delete-site-btn')?.addEventListener('click', () => {
      this.handleDeleteSite();
    });

    // 模态框事件
    this.bindModalEvents();

    // 键盘快捷键
    document.addEventListener('keydown', this.handleKeyboardShortcuts.bind(this));
  }

  private bindModalEvents(): void {
    // 添加网站模态框
    document.getElementById('close-add-site-modal')?.addEventListener('click', () => {
      this.passwordManager.hideAddSiteDialog();
    });

    document.getElementById('cancel-add-site')?.addEventListener('click', () => {
      this.passwordManager.hideAddSiteDialog();
    });

    document.getElementById('confirm-add-site')?.addEventListener('click', () => {
      this.handleAddSite();
    });

    // 设置模态框
    document.getElementById('close-settings-modal')?.addEventListener('click', () => {
      this.passwordManager.hideSettingsDialog();
    });

    document.getElementById('cancel-settings')?.addEventListener('click', () => {
      this.passwordManager.hideSettingsDialog();
    });

    document.getElementById('save-settings')?.addEventListener('click', () => {
      this.handleSaveSettings();
    });

    // 点击遮罩关闭模态框
    document.querySelectorAll('.modal-overlay').forEach(overlay => {
      overlay.addEventListener('click', (e) => {
        if (e.target === overlay) {
          this.passwordManager.hideAddSiteDialog();
          this.passwordManager.hideSettingsDialog();
        }
      });
    });
  }

  private async handleGeneratePassword(): Promise<void> {
    const state = this.passwordManager.getState();
    if (!state.selectedSite) return;

    try {
      const result = await this.passwordManager.generatePassword(state.selectedSite);
      const passwordInput = document.getElementById('generated-password') as HTMLInputElement;
      const copyBtn = document.getElementById('copy-password-btn') as HTMLButtonElement;

      if (passwordInput) {
        passwordInput.value = result.password;
        copyBtn.disabled = false;
      }
    } catch (error) {
      console.error('Failed to generate password:', error);
      alert('密码生成失败: ' + (error instanceof Error ? error.message : '未知错误'));
    }
  }

  private async handleCopyPassword(): Promise<void> {
    const passwordInput = document.getElementById('generated-password') as HTMLInputElement;
    if (!passwordInput.value) return;

    try {
      await navigator.clipboard.writeText(passwordInput.value);

      // 显示复制成功动画
      const copyBtn = document.getElementById('copy-password-btn');
      if (copyBtn) {
        copyBtn.classList.add('copy-success');
        copyBtn.textContent = '✅ 已复制';

        setTimeout(() => {
          copyBtn.classList.remove('copy-success');
          copyBtn.textContent = '📋 复制密码';
        }, 2000);
      }
    } catch (error) {
      console.error('Failed to copy password:', error);
      // 降级到选择文本
      passwordInput.select();
      document.execCommand('copy');
    }
  }

  private handleTogglePasswordVisibility(): void {
    const state = this.passwordManager.getState();
    if (!state.currentUser) return;

    const newShowPassword = !state.currentUser.settings.showPassword;
    this.passwordManager.updateSettings({ showPassword: newShowPassword });
  }

  private handleUpdateSite(): void {
    const state = this.passwordManager.getState();
    if (!state.selectedSite) return;

    const counterInput = document.getElementById('site-counter') as HTMLInputElement;
    const templateSelect = document.getElementById('site-template') as HTMLSelectElement;
    const contextInput = document.getElementById('site-context') as HTMLInputElement;

    const counter = parseInt(counterInput.value);
    if (isNaN(counter) || counter < 1 || counter > 4294967295) {
      alert('计数器必须是1到4294967295之间的数字');
      return;
    }

    this.passwordManager.updateSite(state.selectedSite.id, {
      counter,
      template: templateSelect.value as PasswordTemplate,
      context: contextInput.value.trim() || undefined
    });

    // 清除已生成的密码
    const passwordInput = document.getElementById('generated-password') as HTMLInputElement;
    const copyBtn = document.getElementById('copy-password-btn') as HTMLButtonElement;
    if (passwordInput) {
      passwordInput.value = '';
      copyBtn.disabled = true;
    }
  }

  private handleDeleteSite(): void {
    const state = this.passwordManager.getState();
    if (!state.selectedSite) return;

    if (confirm(`确定要删除网站 "${state.selectedSite.name}" 吗？此操作无法撤销。`)) {
      this.passwordManager.deleteSite(state.selectedSite.id);
    }
  }

  private handleAddSite(): void {
    const nameInput = document.getElementById('new-site-name') as HTMLInputElement;
    const urlInput = document.getElementById('new-site-url') as HTMLInputElement;
    const templateSelect = document.getElementById('new-site-template') as HTMLSelectElement;
    const contextInput = document.getElementById('new-site-context') as HTMLInputElement;

    const name = nameInput.value.trim();
    const siteName = urlInput.value.trim();
    const template = templateSelect.value as PasswordTemplate;
    const context = contextInput.value.trim();

    if (!name || !siteName) {
      alert('请填写网站名称和域名');
      return;
    }

    this.passwordManager.addSite(name, siteName, template, context || undefined);
  }

  private handleSaveSettings(): void {
    const defaultTemplateSelect = document.getElementById('default-template') as HTMLSelectElement;
    const autoLockCheckbox = document.getElementById('auto-lock') as HTMLInputElement;
    const autoLockTimeoutInput = document.getElementById('auto-lock-timeout') as HTMLInputElement;
    const showPasswordCheckbox = document.getElementById('show-password') as HTMLInputElement;

    const timeout = parseInt(autoLockTimeoutInput.value);
    if (isNaN(timeout) || timeout < 1 || timeout > 1440) {
      alert('自动锁定时间必须是1到1440分钟之间的数字');
      return;
    }

    this.passwordManager.updateSettings({
      defaultTemplate: defaultTemplateSelect.value as PasswordTemplate,
      autoLock: autoLockCheckbox.checked,
      autoLockTimeout: timeout,
      showPassword: showPasswordCheckbox.checked
    });

    this.passwordManager.hideSettingsDialog();
  }

  private handleKeyboardShortcuts(event: KeyboardEvent): void {
    // Ctrl/Cmd + G: 生成密码
    if ((event.ctrlKey || event.metaKey) && event.key === 'g') {
      event.preventDefault();
      this.handleGeneratePassword();
    }

    // Ctrl/Cmd + C: 复制密码 (当密码输入框有焦点时)
    if ((event.ctrlKey || event.metaKey) && event.key === 'c') {
      const activeElement = document.activeElement;
      if (activeElement && activeElement.id === 'generated-password') {
        event.preventDefault();
        this.handleCopyPassword();
      }
    }

    // Escape: 关闭模态框
    if (event.key === 'Escape') {
      this.passwordManager.hideAddSiteDialog();
      this.passwordManager.hideSettingsDialog();
    }

    // Ctrl/Cmd + N: 添加新网站
    if ((event.ctrlKey || event.metaKey) && event.key === 'n') {
      event.preventDefault();
      this.passwordManager.showAddSiteDialog();
    }
  }

  private escapeHtml(text: string): string {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }
}

// 初始化应用
new MPWApp();
